package rht

import (
	"context"
	"net/http"
	"time"
)

type HttpServerContextFunc interface {
	context.Context
	Request() HttpServerRequestFunc
	Response() HttpServerResponseFunc
	Store() Store
}

func NewHttpServerContext(w http.ResponseWriter, r *http.Request) HttpServerContextFunc {
	return &httpServerContext{
		ctx:  r.Context(),
		req:  NewHttpServerRequest(r),
		resp: NewHttpServerResponse(w),
	}
}

var _ HttpServerContextFunc = new(httpServerContext)

type httpServerContext struct {
	ctx   context.Context
	req   HttpServerRequestFunc
	resp  HttpServerResponseFunc
	store Store
}

func (h *httpServerContext) Store() Store {
	if h.store == nil {
		h.store = newStore()
	}
	return h.store
}

func (h *httpServerContext) Deadline() (deadline time.Time, ok bool) {
	return h.ctx.Deadline()
}

func (h *httpServerContext) Done() <-chan struct{} {
	return h.ctx.Done()
}

func (h *httpServerContext) Err() error {
	return h.ctx.Err()
}

func (h *httpServerContext) Value(key any) any {
	return h.ctx.Value(key)
}

func (h *httpServerContext) Request() HttpServerRequestFunc {
	return h.req
}

func (h *httpServerContext) Response() HttpServerResponseFunc {
	return h.resp
}
